<template>
  <div class="page-wapper">
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">模块名称：</div>
            <el-input
              v-model="filterData.releaseName"
              size="small"
              placeholder="请输入"
              clearable
              @keyup.enter="handleSearch"
            ></el-input>
          </div>

          <div v-if="$isSupperAdmin()" class="filter_item">
            <div class="label">所属机构：</div>
            <OrgSelect v-model:modelValue="orgInfo" @change="handleSearch" />
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_options_bar">
        <div></div>
        <div>
          <el-button
            v-if="$hasPermission($permission.CASCADE_SAVE_OR_UPDATE)"
            size="mini"
            type="primary"
            @click="createTableData"
          >
            新建
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :tree-config="treeConfig"
          row-id="id"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
        >
          <vxe-column
            field="name"
            title="模块名称"
            :edit-render="{}"
            align="left"
            header-align="center"
            tree-node
          >
          </vxe-column>

          <vxe-column
            field="orderNumber"
            title="排序编号"
            :edit-render="{}"
            width="100"
          >
          </vxe-column>

          <vxe-column #default="{ row }" width="170" title="操作" fixed="right">
            <div>
              <el-button
                v-if="$hasPermission($permission.CASCADE_SAVE_OR_UPDATE)"
                size="mini"
                type="text"
                @click.stop="addChildDataMethod(row)"
              >
                添加下级
              </el-button>
              <!-- <el-button
                v-if="$hasPermission($permission.CASCADE_SAVE_OR_UPDATE)"
                size="mini"
                type="text"
                @click.stop="editTableDataMethod(row)"
              >
                编辑
              </el-button> -->
              <el-button
                v-if="$hasPermission($permission.CASCADE_DELETE)"
                size="mini"
                type="text"
                @click.stop="deleteTableDataMethod(row)"
              >
                删除
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
    </div>

    <!-- 编辑弹框 -->
    <ProjectModuleFormDialog
      ref="projectModuleFormDialogRef"
      @refresh="getTableData"
    />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  nextTick,
  getCurrentInstance,
  toRefs,
  computed,
  onMounted,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import ProjectModuleFormDialog from "./components/ProjectModuleFormDialog.vue";
import OrgSelect from "../../components/OrgSelect.vue";

const initFilterData = () => {
  return {
    releaseName: null,
    orgId: null,
    parentId: null,
  };
};

export default {
  name: "ProjectModuleManage",
  components: { ProjectModuleFormDialog, OrgSelect },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const store = useStore();

    const userInfo = computed(() => store.state.user.userInfo);

    const projectModuleFormDialogRef = ref(null);

    // 机构选择组件绑定的数据
    const orgInfo = ref({
      orgId: null,
      orgName: null,
    });

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});

    const xTable = ref(null);
    const tableData = ref([]);
    const tableLoading = ref(false);
    const searchBtnLoading = ref(false);

    const tableState = reactive({
      treeConfig: {
        // transform: true,
        parentField: "parentId",
        children: "children",
        expandAll: true,
        // loadMethod({ row }) {
        //   console.log("row ==>", row);
        //   // 异步加载子节点
        //   return new Promise((resolve) => {
        //     let parentId;
        //     if (row) {
        //       parentId = row.id;
        //     } else {
        //       parentId = null;
        //     }
        //     $api.cascade
        //       .getCascadeList({
        //         parentId,
        //         orgId: condition.orgId,
        //       })
        //       .then((res) => {
        //         const childs = res.data.map((item) => {
        //           return {
        //             ...item,
        //             hasChild: !!item.childrenId,
        //           };
        //         });
        //         resolve(childs);
        //       })
        //       .catch((err) => {
        //         console.error("getCascadeList error: ", err);
        //       });
        //   });
        // },
      },
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      resetOrgData();
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      // 处理机构搜索参数
      condition.orgId = orgInfo.value.orgId;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      if (!condition.orgId) {
        // ElMessage.warning("请先选择机构");
        tableData.value = [];
        return;
      }
      tableLoading.value = true;
      $api.cascade
        .listTree({
          ...condition,
        })
        .then((res) => {
          tableLoading.value = false;
          tableData.value = res.data.map((item) => {
            return {
              ...item,
              hasChild: !!item.childrenId,
            };
          });
          nextTick(() => {
            xTable.value && xTable.value.setAllTreeExpand(true);
          });
        })
        .catch((err) => {
          tableLoading.value = false;
          console.error("tableData error: ", err);
        });
    };

    // 新建
    const createTableData = () => {
      if (!condition.orgId) {
        return ElMessage.warning("请先选择机构");
      }
      openFormDialog(condition.orgId);
    };

    // 编辑内容
    const editTableDataMethod = (row) => {
      openFormDialog(row.orgId, row);
    };

    const openFormDialog = (orgId, row, isAddChild = false) => {
      nextTick(() => {
        projectModuleFormDialogRef.value.open(orgId, row, isAddChild);
      });
    };

    const closeFormDialog = () => {
      nextTick(() => {
        projectModuleFormDialogRef.value.close();
      });
    };

    // 添加下级
    const addChildDataMethod = (row) => {
      openFormDialog(row.orgId, row, true);
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.name.length > 10 ? row.name.slice(0, 10) + "..." : row.name
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteCascade(row.id);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteCascade = (id) => {
      tableLoading.value = true;
      $api.cascade
        .deleteCascade({
          id,
        })
        .then((res) => {
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteCascade error: ", err);
        })
        .finally(() => {
          tableLoading.value = false;
        });
    };

    // 重置机构绑定数据-初始值为当前登录人绑定的机构信息
    const resetOrgData = () => {
      // 此数据必须在 dom 挂载之后初始化，否则 v-model 绑定数据无法流向子组件
      orgInfo.value.orgId = userInfo.value.orgId;
      orgInfo.value.orgName = userInfo.value.orgName;
    };

    // 初始化
    const initPageData = () => {
      resetOrgData();
      // 必须放在 resetOrgData 之后
      handleSearch();
    };

    onMounted(() => {
      initPageData();
    });

    return {
      xTable,
      tableData,
      tableLoading,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      createTableData,
      getTableData,
      projectModuleFormDialogRef,
      editTableDataMethod,
      deleteTableDataMethod,
      orgInfo,
      addChildDataMethod,
      ...toRefs(tableState),
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}
.handle-row {
  margin-top: 30px;
}
</style>
